from datetime import datetime
from phonik_web.phonik.models import News
from phonik_web.phonik.models import Comment
from django.http import HttpResponse
from django.template import Context, loader
from django.shortcuts import render_to_response, HttpResponseRedirect
from phonik_web.phonik.forms import CommentForm

def news(request):
    news_list = News.objects.all().order_by('-pub_date')[:5]

    for news in news_list:
        news.comments_count = len(Comment.objects.filter(news=news.id))

    return render_to_response('news.html', {'news_list': news_list })


def news_details(request, news_id):
    if request.method == 'POST': # If the form has been submitted...
        comment_form = CommentForm(request.POST) # A form bound to the POST data
        if comment_form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            author = comment_form.cleaned_data['author']
            text = comment_form.cleaned_data['text']

            comment = Comment(news_id=news_id,author=author, text=text, pub_date = datetime.today())
            comment.save()


    news = News.objects.get(pk=1)
    comments = Comment.objects.filter(news=news_id)
    comment_form = CommentForm()
    comment_form.data['news_id'] = news_id
    
    return render_to_response('news_details.html', {'news': news, 'comments': comments, 'comment_form': comment_form })

    
def download(request):
    return render_to_response('download.html', {'news_list': None})


def contact(request):
    news_list = News.objects.all().order_by('-pub_date')[:5]
    return render_to_response('contact.html', {'news_list': None})
